package com.wiserun.RestFul.controller;

import java.util.*;

import com.sun.jndi.ldap.LdapCtxFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.wiserun.common.util.FormatUtil;
import com.wiserun.develop.custom.controller.CustomController;
import com.wiserun.develop.custom.model.Custom;
import com.wiserun.develop.custom.service.CustomService;
import com.wiserun.RestFul.service.RestFulApiCheckService;
import com.wiserun.common.model.ResponseData;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.naming.Context;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;


@Api(description = "restful客户管理接口")
@RestController
@RequestMapping("/customapi")
public class CustomApiController {
	 private static final Logger logger = LoggerFactory.getLogger(CustomController.class);
		@Autowired
		private CustomService service;
		@Autowired
		private RestFulApiCheckService rfac;
		
		@ApiOperation(value = "获取客户列表", notes = "获取客户列表")
	    @RequestMapping(value = "/list", method = { RequestMethod.POST },produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	    public ResponseData getList(@RequestBody JSONObject userEntity) throws Exception {
			logger.info("=========CustomApiController.getList========");
			//先验证权限
			ResponseData rd=rfac.checkAuth(userEntity,"/customapi/list");
			//不为0时为出错
			if(rd.getCode()!=0) {
				//直接返回错误信息
				return rd;
			}
			//继续执行

			//业务逻辑，决定使用哪个service及哪个方法
			Map<String, Object> map = new HashMap<>();
			List<Custom> list=service.getCustomList();
			map.put("list",list);
			logger.info(map.toString());
			logger.info("=========CustomApiController.getList========");
			//输出结果
	        return FormatUtil.success(map);
	    }

	public static void main(String[] args) {
		CustomApiController test = new CustomApiController();
		try {
			Object obj	=test.connetLDAP();
			test.testSearch();
			test.testAddOu();
			System.out.println(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	//ladp 连接器
	public LdapContext connetLDAP() throws NamingException {
		// 连接Ldap需要的信息
		String ldapFactory = "com.sun.jndi.ldap.LdapCtxFactory";
		String ldapUrl = "ldap://10.4.1.177:389";// url
		String ldapAccount = "pncs\\ldaptest"; // 用户名
		String ldapPwd = "Ltest123!@#";//密码
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, ldapFactory);
		// LDAP server
		env.put(Context.PROVIDER_URL, ldapUrl);
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL, ldapAccount);
		env.put(Context.SECURITY_CREDENTIALS, ldapPwd);
		env.put("java.naming.referral", "follow");
		LdapContext ctxTDS = new InitialLdapContext(env, null);
		return ctxTDS;
	}

	//查询
	public void testSearch() throws Exception {
		LdapContext ctx = connetLDAP();
		// 设置过滤条件
		String uid = "ldaptest";
		String filter = "(&(objectClass=top)(objectClass=organizationalPerson)(uid=" + uid + "))";
		// 限制要查询的字段内容
		String[] attrPersonArray = { "uid", "userPassword", "displayName", "cn", "sn", "mail", "description" };
		SearchControls searchControls = new SearchControls();
		searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		// 设置将被返回的Attribute
		searchControls.setReturningAttributes(attrPersonArray);
		// 三个参数分别为：
		// 上下文；
		// 要搜索的属性，如果为空或 null，则返回目标上下文中的所有对象；
		// 控制搜索的搜索控件，如果为 null，则使用默认的搜索控件
		String name = "ou=LDAPTest,dc=pncs,dc=local";
		NamingEnumeration<NameClassPair> answer = ctx.list(name);
		System.out.println("开始循环");
		// 输出查到的数据

		while (answer.hasMore()) {
			NameClassPair result = answer.next();
			String attrs = result.getName();
			System.out.println(attrs);
		}
	}

	// 添加用户
	public void testAdd() throws Exception {
		LdapContext ctx = connetLDAP();
		int UF_ACCOUNTDISABLE = 0x0002;
		int UF_PASSWD_NOTREQD = 0x0020;
		int UF_PASSWD_CANT_CHANGE = 0x0040;
		int UF_NORMAL_ACCOUNT = 0x0200;
		int UF_DONT_EXPIRE_PASSWD = 0x10000;
		int UF_PASSWORD_EXPIRED = 0x800000;
		Attributes attrs = new BasicAttributes(true);
		Attribute objclass = new BasicAttribute("objectclass");
		// 添加ObjectClass
		String[] attrObjectClassPerson = { "user"};
		Arrays.sort(attrObjectClassPerson);
		for (String ocp : attrObjectClassPerson) {
			objclass.add(ocp);
		}
		attrs.put(objclass);
		String uid = "test36";
		String userDN =  "cn="+uid+",ou=LDAPTest,dc=pncs,dc=local";
		// 密码处理
		// attrs.put("uid", uid);
		attrs.put("uid", "tetttttt");
		//attrs.put("cn", uid);
		attrs.put("userPrincipalName", uid+"@pncs.local");
		attrs.put("sAMAccountName", uid);
		attrs.put("sn", uid);
		attrs.put("displayName", "张wfei");
		attrs.put("mail", "abc@1w63.com");
		attrs.put("description", "测试添加w");//描述
		attrs.put("userPassword", "123456".getBytes("UTF-8"));
		attrs.put("userAccountControl", Integer.toString(UF_DONT_EXPIRE_PASSWD+UF_NORMAL_ACCOUNT+UF_PASSWD_NOTREQD));
		ctx.createSubcontext(userDN, attrs);

	}


	// 添加组织单元
	public void testAddOu() throws Exception {
		LdapContext ctx = connetLDAP();
/*		int UF_ACCOUNTDISABLE = 0x0002;
		int UF_PASSWD_NOTREQD = 0x0020;
		int UF_PASSWD_CANT_CHANGE = 0x0040;
		int UF_NORMAL_ACCOUNT = 0x0200;
		int UF_DONT_EXPIRE_PASSWD = 0x10000;
		int UF_PASSWORD_EXPIRED = 0x800000;


 */
		Attributes attrs = new BasicAttributes(true);
		Attribute objclass = new BasicAttribute("objectclass");
		// 添加ObjectClass
		String[] attrObjectClassPerson = { "organizationalUnit"};
		Arrays.sort(attrObjectClassPerson);
		for (String ocp : attrObjectClassPerson) {
			objclass.add(ocp);
		}
		attrs.put(objclass);
		String uid = "testOU";
		String userDN =  "ou=uuuu,ou=LDAPTest,dc=pncs,dc=local";
		// 密码处理
		//attrs.put("name", uid);
		/*
		attrs.put("uid", "tetttttt");
		//attrs.put("cn", uid);
		attrs.put("userPrincipalName", uid+"@pncs.local");
		attrs.put("sAMAccountName", uid);
		attrs.put("sn", uid);
		attrs.put("displayName", "张wfei");
		attrs.put("mail", "abc@1w63.com");
		attrs.put("description", "测试添加w");//描述
		attrs.put("userPassword", "123456".getBytes("UTF-8"));
		attrs.put("userAccountControl", Integer.toString(UF_DONT_EXPIRE_PASSWD+UF_NORMAL_ACCOUNT+UF_PASSWD_NOTREQD));
*/
		ctx.createSubcontext(userDN,attrs);

	}

}
